Here’s a comprehensive Pydantic cheatsheet that covers the most important features and use cases. This should serve as a quick reference for your future Pydantic projects.
Pydantic Cheatsheet
Pydantic Available Types
Pydantic’s BaseModel can contain a variety of specific types, allowing you to define models that validate and serialize data effectively. Here’s a breakdown of the types you can use in Pydantic models, including whether np.float (from NumPy) can be included.
Common Types in Pydantic
Basic Types:
int: Integer values.
float: Floating-point numbers.
str: Strings.
bool: Boolean values.
Optional Types:
Optional[type]: Indicates that a field can be of a specified type or None.
Example: Optional[str] means the field can be a string or None.
Constrained Types:
conint: Constrained integer (e.g., conint(gt=0) for integers greater than 0).
confloat: Constrained float (e.g., confloat(ge=0.0) for floats greater than or equal to 0).
constr: Constrained string (e.g., constr(min_length=1) for non-empty strings).
Collections:
List[type]: A list of items of a specified type.
Tuple[type1, type2]: A tuple with specified types.
Set[type]: A set of items of a specified type.
Dict[key_type, value_type]: A dictionary with specified key and value types.
Custom Types:
You can define your own classes and use them as types in Pydantic models.
Enums:
You can use Enum types to define a set of named constants.
Using NumPy Types
np.float: While Pydantic does not directly support NumPy types like np.float, you can use Python’s built-in float type instead. If you need to work with NumPy arrays or specific NumPy types, you can convert them to standard Python types when creating your Pydantic model.
Example of a Pydantic Model
Here’s an example of a Pydantic model using various types:
python
1 2 3 4 5 6 7 8 9 10 11 12 13
from pydantic import BaseModel, conint, confloat from typing import List, Optional
In Pydantic, the ge parameter in the Field function stands for “greater than or equal to.” You can use similar constraints to enforce various conditions on your fields. Here are some common constraints you can use:
gt: Greater than
lt: Less than
le: Less than or equal to
ge: Greater than or equal to (as you mentioned)
min_length: Minimum length for strings
max_length: Maximum length for strings
regex: Regular expression for string validation
multiple_of: Value must be a multiple of a specified number
Example Usage
Here’s how you might use some of these constraints in your Product model:
python
1 2 3 4 5 6 7 8 9
from pydantic import BaseModel, Field from typing import Optional
classProduct(BaseModel): name: str description: Optional[str] = None price: float = Field(default=0.0, ge=0) # Price must be >= 0 stock: int = Field(default=0, ge=0) # Stock must be >= 0 sku: str = Field(..., min_length=5, max_length=10) # SKU must be between 5 and 10 characters
Explanation
ge=0: Ensures that the price and stock fields cannot be negative.
min_length=5: Ensures that the sku field has at least 5 characters.
max_length=10: Ensures that the sku field does not exceed 10 characters.
# Define the Pydantic model classUser(BaseModel): name: str age: int email: str
# Load data from YAML file with open('data.yaml', 'r') as file: yaml_data = yaml.safe_load(file)
# Create an instance of the Pydantic model user = User(**yaml_data)
# Print the user instance print(user)
This cheatsheet covers a wide range of Pydantic features and use cases. It includes basic model definition, field types and validations, nested models, custom validators, configuration options, JSON handling, and more advanced features like custom root types and complex validations.
You can use this as a quick reference when working with Pydantic in your projects. Remember to import the necessary modules and classes as shown in the examples. As Pydantic evolves, some syntax or features might change, so it’s always a good idea to refer to the official documentation for the most up-to-date information.